package com.heima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.result.PageResult;
import com.heima.mapper.OrderMapper;
import com.heima.pojo.dto.OrderQueryDTO;
import com.heima.pojo.entity.Order;
import com.heima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;


/**
 * \* User: chy
 * \* Date: 2025/8/23  15:51
 * \* Description:
 * \
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    /**
     * 订单列表
     * @param orderPageDTO
     * @return
     */
    @Override
    public PageResult<Order> pageResultOrder(OrderQueryDTO orderPageDTO) {
        // 设置分页参数
        Page<Order> page = new Page<>(orderPageDTO.getPageIndex(), orderPageDTO.getPageSize());

        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<Order>()
                .like(StringUtils.isNotBlank(orderPageDTO.getOrderNo()), Order::getOrderNo, orderPageDTO.getOrderNo())
                .ge(orderPageDTO.getStartDate() != null, Order::getCreateTime, toLocalDateTimeStart(orderPageDTO.getStartDate()))
                .le(orderPageDTO.getEndDate() != null, Order::getCreateTime, toLocalDateTimeEnd(orderPageDTO.getEndDate()));

        Page<Order> orderPage = this.page(page, wrapper);

        return PageResult.<Order>builder()
                .totalCount((int)orderPage.getTotal())
                .totalPage((int)orderPage.getPages())
                .pageIndex(orderPageDTO.getPageIndex())
                .pageSize(orderPageDTO.getPageSize())
                .currentPageRecords(orderPage.getRecords())
                .build();
    }

    // 工具方法 ,因为前端传的日期格式yyyy-MM-dd,而数据库中返回的日期格式为yyyy-MM-dd HH:mm:ss,所以需要转换
    private LocalDateTime toLocalDateTimeStart(LocalDate date) {
        return date != null ? LocalDateTime.of(date, LocalTime.MIN) : null;
    }

    private LocalDateTime toLocalDateTimeEnd(LocalDate date) {
        return date != null ? LocalDateTime.of(date, LocalTime.MAX) : null;
    }
}
